from netmiko import ConnectHandler
from netmiko import BaseConnection
from textfsm import TextFSM
from vender.cisco.textfsm import textFsmPath

# 登录一台设备，获取信息
# 获取接口下配置
# 获取 LLDP 邻居信息
# 获取 MAC 地址表信息
# 获取 ARP 表项信息

class DeviceQuery():

    def __init__(self, device_info: any) -> None:

        self.vender = device_info['__vender']
        device_info.pop('__vender')
        self.device_info = device_info

    def __connectDevice(self) -> BaseConnection:

        try:
            ssh_session = ConnectHandler(**self.device_info)
            return ssh_session

        except Exception as err:
            print(f'发生错误,详情：{err}')

    # 文本过滤器
    def __TextFilter(self, _templatePath: str, _text: str) -> list:

        try:
            template = TextFSM(open(_templatePath))
            data = template.ParseTextToDicts(_text)
            data.insert(0, template.header)
            return data

        except Exception as err:
            print(f'发生错误,详情：__TextFilter {err}')
    
    def __drumWash (self, instruct: str) -> list:

        try:
            # 根据 self.vender 传值确定厂商对应的数据
            ssh = self.__connectDevice()
            output = ssh.send_command(textFsmPath[self.vender][instruct]['command'])
            ssh.disconnect()
            data = self.__TextFilter(textFsmPath[self.vender][instruct]['textfsm'], output)
            return data

        except Exception as err:
            print(f'发生错误,详情：{err}')

    # 查询接口 ipv4 地址数据，cisco [show ip int brief] huawei [display ip inter biref]
    def query_inter_ipv4(self) -> list:

        try:
            return self.__drumWash('ip_interface')

        except Exception as err:
            print(f'发生错误,详情：{err}')

    # 查询 lldp 数据，IP地址查询信息错误未修复
    def query_lldp_info(self) -> list:
        try:
            return self.__drumWash('lldp_neighbors')

        except Exception as err:
            print(f'发生错误,详情：{err}')

    # 查询 ospf 邻居
    def query_ospf_neighbors(self) -> list:
        try:
            return self.__drumWash('ospf_neighbors')

        except Exception as err:
            print(f'发生错误,详情：{err}')

    # 有报错，未修复
    def query_env_temperature(self) -> list:
        try:
            return self.__drumWash('env_temperature')

        except Exception as err:
            print(f'发生错误,详情：{err}')






